package net.uhuijia.user.usermall.controller;

import net.uhuijia.enums.UserIdentity;
import net.uhuijia.utils.HttpClientHelper;
import net.uhuijia.utils.JsonHelper;
import net.uhuijia.vo.OpenidUnionidVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import net.uhuijia.appbase.controller.BaseController;
import net.uhuijia.enums.ErrorCodeEnum;
import net.uhuijia.exception.BusinessException;
import net.uhuijia.user.usermall.persistence.model.UserMall;
import net.uhuijia.user.usermall.persistence.model.UserMallExample;
import net.uhuijia.user.usermall.service.UserMallService;
import net.uhuijia.user.usertoken.persistence.model.UserToken;
import net.uhuijia.user.usertoken.service.UserTokenService;
import net.uhuijia.user.userverifycode.service.UserVerifycodeService;
import net.uhuijia.user.userwxauth.persistence.model.UserWxauth;
import net.uhuijia.user.userwxauth.service.UserWxauthService;
import net.uhuijia.user.userwxopen.persistence.model.UserWxopen;
import net.uhuijia.user.userwxopen.service.UserWxopenService;
import net.uhuijia.utils.StringHelper;
import net.uhuijia.vo.ResultMapVo;
import net.uhuijia.vo.user.usermall.param.LoginParamVo;
import net.uhuijia.vo.user.usermall.returnvo.TokenReturnVo;

/**
 * 用户信息类
 * @author 许小宝
 */
@RestController
@RequestMapping(value="/usermall")
public class UserMallController
     extends BaseController<UserMallService, UserMall, UserMallExample> {
	/**
	 * 用户基本资料服务
	 */
	private UserMallService userMallService;
	@Autowired
	public void setUserMallService(UserMallService userMallService) {
		this.userMallService = userMallService;
	}

	/**
	 * 用户登入令牌服务
	 */
	private UserTokenService userTokenService;
	@Autowired
	public void setUserTokenService(UserTokenService userTokenService) {
		this.userTokenService = userTokenService;
	}

	/**
	 * 微信开放平台服务
	 */
	private UserWxopenService userWxopenService;
	@Autowired
	public void setUserWxopenService(UserWxopenService userWxopenService) {
		this.userWxopenService = userWxopenService;
	}

	/**
	 * 微信公众号、小程序服务
	 */
	private UserWxauthService userWxauthService;
	@Autowired
	public void setUserWxauthService(UserWxauthService userWxauthService) {
		this.userWxauthService = userWxauthService;
	}

	/**
	 * 验证码服务
	 */
	private UserVerifycodeService userVerifycodeService;
	@Autowired
	public void setUserVerifycodeService(UserVerifycodeService userVerifycodeService) {
		this.userVerifycodeService = userVerifycodeService;
	}

	/**
	 * 用户编辑个人资料信息
	 * @param user 用户属性作为参数
	 * @return ResultMapVo<?> 通用返回值
	 */
	@RequestMapping(value = "/editor")
    @ResponseBody
	public ResultMapVo<?> editor( UserMall user ){
		UserMall dbUser = this.getUserMallByTokenAndDevice();
		user.setId(dbUser.getId());
		userMallService.edit(user);
		return ResultMapVo.ok();
	}
	
	/**
	 * 微信授权信息(公众号与小程序时用到)
	 * @param phone 手机号码
	 * @return ResultMapVo<?> 通用返回值
	 */
	@RequestMapping(value = "/sendCode")
    @ResponseBody
	public ResultMapVo<?> sendCode( String phone ) {
		if( StringHelper.isNotBlanks(phone) ){
			userVerifycodeService.sendCodeByCx(phone);
			return ResultMapVo.ok();
		}else{
			throw new IllegalArgumentException();
		}
	}

	/**
	 * 微信授权信息(公众号与小程序时用到)
	 * @param param 微信授权参数信息
	 * @return ResultMapVo<?> 通用返回值
	 */
	@RequestMapping(value = "/wxauth")
    @ResponseBody
	public ResultMapVo<?> wxauth( UserWxauth param ) {
		if( StringHelper.isNotBlanks(param.getAuthAppid(),param.getAuthOpenid()) ){
			userWxauthService.addWxauth(param);
			return ResultMapVo.ok();
		}else{
			throw new IllegalArgumentException();
		}
	}

	/**
	 * 微信授权信息（微信开放平台时用到）
	 * @param param 微信开放平台参数
	 * @return ResultMapVo<?> 通用返回值
	 */
	@RequestMapping(value = "/wxopen")
    @ResponseBody
	public ResultMapVo<?> wxopen( UserWxopen param ) {
		if( StringHelper.isNotBlanks(param.getAuthUnionid(),param.getGhId()) ){
			userWxopenService.addWxopen(param);
			return ResultMapVo.ok();
		}else{
			throw new IllegalArgumentException();
		}
	}

	/**
	 * 微信授权数据解密
	 * @param encryptedData 加密的数据
	 * @param iv 偏移量
	 * @param code 授权码
	 * @param appid 微信appid
	 * @param secret 微信密钥
	 * @return ResultMapVo<OpenidUnionidVo>
	 */
	@RequestMapping(value = "/encryptedData")
	@ResponseBody
	public ResultMapVo<OpenidUnionidVo> encryptedData( String encryptedData,String iv,String code,String appid,String secret) {
		if( StringHelper.isNotBlanks(encryptedData,iv,code,appid,secret) ){
			String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret+"&js_code=" + code+"&grant_type=authorization_code";
			String res = HttpClientHelper.get(url);
			OpenidUnionidVo openidUnionidVo = JsonHelper.toObject(res, OpenidUnionidVo.class);
			return ResultMapVo.ok(openidUnionidVo);
		}else{
			throw new IllegalArgumentException();
		}
	}
	
	/**
	 * 验证 token秘 device 如果成功则返回用户信息，如果失败返回空
	 * @param param 用户 登入参数对象
	 * @return ResultMapVo<TokenReturnVo> 通用返回值
	 */
	@RequestMapping(value = "/login")
    @ResponseBody
	public ResultMapVo<TokenReturnVo> login( LoginParamVo param ) {
		UserMall user = null;
		// 1  device token         直接使用token登入
		if( StringHelper.isNotBlanks(param.getToken(),param.getDevice()) ){
			user = userTokenService.auth( param.getDevice(),param.getToken() );
		}
		//2  device phone   code  手机号码与短信验证码快捷登入
		if( StringHelper.isNotBlanks( param.getDevice(),param.getPhone(),param.getCode()) ){
			if( userVerifycodeService.isEffectiveCode(param.getPhone(), param.getCode()) ){
				UserMall tempUser = userMallService.getByPhone(param.getPhone());
				if( null == tempUser ){
					user = userMallService.reg(param);
				}else{
				    user = tempUser;
				}
			}else{
				throw new BusinessException(ErrorCodeEnum.verifycode_error);
			}
		}
		//3  device phone   pwd   手机号码与密码登入
		if( StringHelper.isNotBlanks(param.getDevice(),param.getPhone(),param.getPwd()) ){
			user = userMallService.getByPhonePwd(param.getPhone(),param.getPwd());
			if( null == user ){
				throw new BusinessException(ErrorCodeEnum.account_pwd_error);
			}
		}
		// 4  device email   pwd   邮箱名称与密码登入
		if( StringHelper.isNotBlanks(param.getDevice(),param.getEmail(),param.getPwd()) ){
			user = userMallService.getByEmailPwd(param.getEmail(),param.getPwd());
			if( null == user ){
				throw new BusinessException(ErrorCodeEnum.account_pwd_error);
			}
		}
		//5  device number  pwd   用户编号与密码登入
		if( StringHelper.isNotBlanks(param.getDevice(),param.getNumber(),param.getPwd())){
			user = userMallService.getByNumberPwd(param.getNumber(),param.getPwd());
			if( null == user ){
				throw new BusinessException(ErrorCodeEnum.account_pwd_error);
			}
		}
		// 6 device unionid ghid      微信开放平台授权登入
		if( StringHelper.isNotBlanks(param.getDevice(),param.getUnionid(),param.getGhid()) ){
			UserWxopen wxopen = userWxopenService.getByUnionidAndGhid(param.getUnionid(), param.getGhid());
			if( null != wxopen && StringHelper.isNotBlanks(wxopen.getUserId()) ){
				user = userMallService.get(wxopen.getUserId());
			}else{
				throw new BusinessException(ErrorCodeEnum.wxauth_error);
			}
		}
		//7  device openid appid      微信公众号、小程序授权登入
		if( StringHelper.isNotBlanks(param.getDevice(),param.getAppid(),param.getOpenid()) ){
			UserWxauth wxauth = userWxauthService.getByAppidAndOpenid(param.getAppid(),param.getOpenid());
			if( null != wxauth && StringHelper.isNotBlanks(wxauth.getUserId()) ){
				user = userMallService.get(wxauth.getUserId());
			}else{
				throw new BusinessException(ErrorCodeEnum.wxauth_error);
			}
		}
		TokenReturnVo vo = new TokenReturnVo();
		if( null != user ){
			//创建token
			UserToken createToken = userTokenService.createToken(user, param.getDevice());
			vo.setAccessToken(createToken.getAccessToken());
			vo.setExpiredTime(createToken.getExpiredTime());
			this.setUserMallAuthInfoToRedis(user,createToken.getAccessToken(),createToken.getDevice());
			return ResultMapVo.ok(vo);
		}else{
			throw new BusinessException(ErrorCodeEnum.login_error);
		}
	}

	/**
	 * 检测用户身份
	 * @param identity  需要检测的身份
	 * @return
	 */
	@RequestMapping(value = "/checkUserIdentity",method = RequestMethod.GET)
	@ResponseBody
	public ResultMapVo<Boolean>  checkUserMallIIdentity(String identity){
		UserIdentity userIdentity =null;
		if( (userIdentity = UserIdentity.getUserIdentityByIdentity(identity))==null) {
			throw  new IllegalArgumentException();
		}
		UserMall userMall = this.getUserMallByTokenAndDevice();
		boolean flag= this.userMallService.checkUserMallIIdentity(userMall,userIdentity);
		return ResultMapVo.ok(flag);
	}


	
}